package com.yyx.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yyx.server.config.component.JwtTokenUtil;
import com.yyx.server.mapper.AdminRoleMapper;
import com.yyx.server.mapper.RoleMapper;
import com.yyx.server.pojo.Admin;
import com.yyx.server.mapper.AdminMapper;
import com.yyx.server.pojo.AdminRole;
import com.yyx.server.pojo.Role;
import com.yyx.server.service.AdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yyx.server.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author YongXin
 * @since 2021-07-24
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private AdminRoleMapper adminRoleMapper;
    /**
     * 登录之后返回token
     * @param username
     * @param password
     * @param request
     * @return
     */
    @Override
    public ResultVo login(String username, String password,String code,HttpServletRequest request) {
        String captcha = (String) request.getSession().getAttribute("captcha");
        System.out.println("-----------");
        System.out.println(captcha);
        System.out.println(code);
        if (StringUtils.isEmpty(captcha)||!captcha.equalsIgnoreCase(code)){
            return ResultVo.error("验证码错误，请重新输入");
        }
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (null==userDetails || !passwordEncoder.matches(password,userDetails.getPassword())){
            return ResultVo.error("用户名或密码不正确");
        }
        if (!userDetails.isEnabled()){
            return ResultVo.error("该账号已被禁用！");
        }
        //更新security登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        HashMap<String, String> map = new HashMap<>();
        map.put("token",token);
        return ResultVo.success("登录成功",map);
    }

    /**
     * 根据用户姓名名获取用户信息
     * @param name
     * @return
     */
    @Override
    public Admin getAdminByUserName(String name) {
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("username",name)
                .eq("enabled",true);
        return adminMapper.selectOne(wrapper);
    }

    /**
     * 根据用户ID查询角色列表
     * @param adminId
     * @return
     */
    @Override
    public List<Role> getRoles(Integer adminId) {

        return roleMapper.getRoles(adminId);
    }

    /**
     * 获取所有或模糊搜索操作员
     * @param keywords
     * @return
     */
    @Override
    public List<Admin> getAllAdmins(String keywords) {
        Integer currentId = ((Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();
        return adminMapper.getAllAdmins(currentId,keywords);
    }

    /**
     * 更新操作员角色
     * @param aid
     * @param rids
     * @return
     */
    @Override
    public ResultVo updAdminRoles(Integer aid, Integer[] rids) {
        adminRoleMapper.delete(new QueryWrapper<AdminRole>().eq("aid",aid));
        Integer result = adminRoleMapper.insertAdminRoles(aid, rids);
        if (rids.length==result){
            return ResultVo.success("更新成功");
        }
        return ResultVo.error("更新失败");
    }

    @Override
    public ResultVo updateAdmin(Admin admin) {
        String encodePsw = passwordEncoder.encode(admin.getPassword());
        admin.setPassword(encodePsw);
        int i = adminMapper.updateById(admin);
        if (i == 1){
            return ResultVo.success("更新成功");
        }
        return ResultVo.error("更新失败");
    }

    /**
     * 更新用户密码
     * @param oldPass
     * @param pass
     * @param adminId
     * @return
     */
    @Override
    public ResultVo updAdminPassword(String oldPass, String pass, Integer adminId) {
        Admin admin = adminMapper.selectById(adminId);
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if (passwordEncoder.matches(oldPass,admin.getPassword())) {
            admin.setPassword(passwordEncoder.encode(pass));
            int i = adminMapper.updateById(admin);
            if (i == 1){
                return ResultVo.success("更新成功");
            }
        }
        return ResultVo.error("更新失败");
    }

    /**
     * 更新用户头像
     * @param url
     * @param id
     * @param authentication
     * @return
     */
    @Override
    public ResultVo updAdminFace(String url, Integer id, Authentication authentication) {
        Admin admin = adminMapper.selectById(id);
        admin.setUserFace(url);
        int i = adminMapper.updateById(admin);
        if (1 == i){
            Admin principal = (Admin) authentication.getPrincipal();
            principal.setUserFace(url);
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(principal,null,authentication.getAuthorities()));
            return ResultVo.success("更新成功",url);
        }
        return ResultVo.error("更新失败");
    }


}
